<template>
  <div >
    <div v-if="messageStatus">
        <n-card title="充值插件" header>
        <div class="header">
            <div>
            <NButton type="primary" @click="onClickAdd">
                添加充值
            </NButton>
             <NButton style="margin:0 20px" @click="rechargeShow = true">
                用户充值
            </NButton>
            </div>
            <div>
            <n-input-group>
                <n-input v-model:value="params.keyword" clearable placeholder="请输入插件关键词" :style="{ width: '100%' }" />
                <n-button @click="List" type="primary" ghost>
                    搜索
                </n-button>
                </n-input-group>
            </div>
        </div>
        </n-card>
        <div class="box">
        <!-- 数据表 -->
        <div class="table-box">
            <div >
            <n-data-table
                striped 
                :loading="messageParams.loading"
                ref="table"
                :columns="columns"
                :data="data"
            />
            </div>
            <div class="pagination">
                <div>共{{pagination.total}}条数据</div>
                <div>
                <n-pagination
                v-model:page="params.pageNum"
                v-model:page-size="params.pageSize"
                :page-count="setPagination(pagination.total,params.pageSize )"
                show-size-picker
                :page-sizes="pageSizes"
                :on-update:page="pageNext"
                :on-update:page-size="sizeNext"
                />
                </div>
            </div>
        
        </div> 
            

        </div>
    </div>

    <div v-else class="Message">
        <n-result
            status="403"
            title="403 禁止访问"
            description="总有些门是对你关闭的"
        >
            <template #footer>
            <n-button @click="goTo('/pluginAdmin/all')">去充钱</n-button>
            </template>
        </n-result>
    </div>

  

 <yingModal  :title="popTitle" @close="cancelCallback" @confirm="submitCallback" :SkuShow="showModal" >
        <template #content>
           <n-form
          ref="formRef"
          :model="formValue"
          :rules="rules"
        >
          <n-form-item label="充值金额" path="currency_balance">
            <n-input v-model:value="formValue.currency_balance" placeholder="请输入充值金额" />
          </n-form-item>

           <n-form-item label="支付金额" path="payment_cash">
            <n-input v-model:value="formValue.payment_cash" placeholder="请输入支付金额" />
          </n-form-item>

            <n-form-item label="赠送金额" path="give_cash">
            <n-input v-model:value="formValue.give_cash" placeholder="请输入赠送金额" />
          </n-form-item>

          <n-form-item label="充值方式" path="currency_balance">
            <n-select v-model:value="formValue.recharge_type"
              :style="{ width: '400px' }" 
              filterable 
              placeholder="请选择充值类型"
              :options="Options"
              clearable
            />
          </n-form-item>

           <n-form-item label="排序" path="sort">
           <n-input v-model:value="formValue.sort" placeholder="请输入" />
          </n-form-item>

          <n-form-item label="渠道" path="currency_balance">
            <n-select v-model:value="formValue.channel"
              :style="{ width: '400px' }" 
              filterable 
              placeholder="请选择渠道"
              :options="Options1"
              clearable
            />
          </n-form-item>

          <n-form-item label="状态">
            <n-switch v-model:value="formValue.status">
              <template #checked>
                启动
              </template>
              <template #unchecked>
                禁用
            </template>
            </n-switch>
          </n-form-item>
        </n-form>
        </template>
    </yingModal>

    <yingModal  :title="'用户充值'" @close="rechargeShow=false" @confirm="rechargeAdd" :SkuShow="rechargeShow" >
        <template #content>
          <div class="box-recharge">
      <div>
        <div style="display: flex;gap:20px;padding:20px 0">
          <div>用户选择</div>
          <div>
            <n-input-group>
                  <n-input v-model:value="inputKeyword" clearable placeholder="请输入用户" :style="{ width: '100%' }" />
                  <n-button @click="find_user" type="primary" ghost>
                      搜索
                  </n-button>
              </n-input-group>
          </div>
        </div>
         <n-radio-group v-if="userList.length" @update:value="rechargeSelect1" v-model:value="openid"  name="radiogroup">
           <div class="rechargeBox">
              <n-radio v-for="item in userList.slice(0,8)" :key="item.openid" :value="item.openid">
                <div class="rechargeItem">
                    <div style="display: flex;justify-content: center;align-items: center;">
                      <div >
                         <n-image
                          :preview-disabled="true"
                          style="object-fit: contain;display: flex;height: 48px;width: 48px;
                              justify-content: center;
                              align-items: center;"
                          :src="item.head_img"/>
                      </div>
                      <div style="margin-left:20px">
                          <div>{{item.nickName}}</div>
                          <div>{{item.phone?(item.phone ):'暂无'}}</div>
                      </div>
                    
                    </div>
                  </div>
              </n-radio>
          </div>  
        </n-radio-group>
         <div v-else>暂无数据</div>
      </div>
      <div>
        <div>充值余额</div>
         <n-radio-group v-if="data.length" @update:value="rechargeSelect" v-model:value="value" name="radiogroup">
           <div class="rechargeBox">
              <n-radio v-for="item in data" :key="item.id" :value="item.id">
                <div class="rechargeItem">
                    <div>
                      <div>充值金额:{{item.currency_balance}}</div>
                      <div>赠送金额:{{item.give_cash}}</div>
                    </div>
                  </div>
              </n-radio>
          </div>  
        </n-radio-group>
        <div v-else>暂无数据</div>
      </div>
       
      </div>
        </template>
    </yingModal>

    <yingModal  :title="'文件管理'" @close="uploadShow=false" @confirm="uploadShow=false" :SkuShow="uploadShow" >
        <template #content>
          <Upload type="1" @selectImage="selectImageFun"/>
        </template>
    </yingModal>
  </div>
</template>

<script setup lang="ts">
import yingModal from "@/components/common/YingModal.vue"
import { NAvatar, NButton, NImage, NSwitch, NTag  } from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { nextTick, onMounted, ref } from 'vue'
import { Https,setPagination } from "@/utils"
import api from './api'
import Upload from "@/views/upload/index.vue"
const router = useRouter()
const route = useRoute()
const pluginInfo = ref({})
const messageStatus = ref(false)
const uploadShow = ref(false)

const Options = ref([
  {
    label:'微信支付',
    value:'微信支付'
  },
  {
    label:'支付宝支付',
    value:'支付宝支付'
  }, 
  {
    label:'其它支付',
    value:'其它支付'
  }, 
])

const Options1 = ref([
  {
    label:'小程序',
    value:'小程序'
  },
  {
    label:'PC',
    value:'PC'
  },{
    label:'其它',
    value:'其它'
  }, 

])
onMounted(() => {
     
    myPluin()
})

const value = ref('')

const selectImageFun =(selectImageList) =>{
   
  formValue.value.level_logo = selectImageList[0];  // 只获取第一张图
  uploadShow.value = false
} 

async function myPluin(){
  const res: any = await api.checkPluginApi({
    plugin_id:route.query.plugin_id,
    user_id:route.query.user_id,
  })
    
  if(res.code == 200 && res.data){
    pluginInfo.value = route.query
    params.value.user_id = route.query.user_id
    params.value.plugin_id = route.query.plugin_id
    messageStatus.value = true;
    List();
    find_user();
  }else{
    messageStatus.value = false;
  }

}
const userList = ref([])
const inputKeyword = ref('')
async function find_user(){
  const res: any = await api.find_userApi({
    user_id:route.query.user_id,
    keyword:inputKeyword.value
  })
    
  if(res.code == 200 && res.data){
    userList.value = res.data.list
  }
}



const pageSizes = [
  {
    label: '10 每页',
    value: 10
  },
  {
    label: '20 每页',
    value: 20
  },
  {
    label: '30 每页',
    value: 30
  },
  {
    label: '40 每页',
    value: 40
  }
]


const pagination = ref({
  total:10
  
})
const formRef = ref<FormInst | null>(null);
const rechargeDataItem = ref('')
const rechargeSelect = (Id) =>{

  data.value.forEach((item, index) =>{

    if(item.id == Id){
      rechargeDataItem.value = item
    }
  });
 
  
}
const openid = ref('')
const rechargeSelect1 = (Id) =>{
  openid.value = Id
   
}

const showModal = ref(false);
const popTitle:any = ref('添加充值');
const params = ref({
  pageNum: 1,
  pageSize: 10,
  keyword: '',
  user_id:''
})

const formValue = ref({
  currency_balance:"",
  payment_cash:"",
  give_cash:"",
  recharge_type:"",
  JSONData:"",
  channel:"",
  status:true,
  sort:"",
})

const rules = {
    currency_balance: {
        
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    channel: {
        type: 'array',
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    sort: {
    
      required: true,
      message: '请输入',
      trigger: 'blur'
    },
    payment_cash: {
     
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    give_cash: {
       
        required: true,
        message: '请输入',
        trigger: 'blur'
    },
    JSONData: {
        required: true,
        message: '请输入副标题',
        trigger: 'blur'
    },
  
}

const columns = [
  {
    title: 'id',
    key: 'id',
    ellipsis: {
      tooltip: true
    }
 
  },
  {
    title: '充值金额',
    key: 'currency_balance',
    ellipsis: {
      tooltip: true
    }
 
  },
  {
    title: '支付金额',
    key: 'payment_cash',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
  },
  {
    title: '赠送金币',
    key: 'give_cash',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
    
  },
 
  {
    title: '充值类型',
    key: 'recharge_type',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
     
  },
   {
    title: '渠道',
    key: 'channel',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
  },
  {
    title: '其它参数',
    key: 'JSONData',
    // width: 200,
    ellipsis: {
      tooltip: true
    },
    
  },
  {
    title: '状态',
    key: 'status',
    ellipsis: {
      tooltip: true
    },
    render: (item) => setStatus(item)
  },
  
  {
    title: '操作',
    key: 'actions',
    width: 360,
    align: 'right',
    fixed: 'right',
    hideInExcel: true,
  
    render(row) {
      return [
      
        h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            style: 'margin-left: 12px;',
            secondary: true,
            onClick: () => handleOpenRolesSet(row),
          },
          {
            default: () => '编辑',
            icon: () => h('i', { class: 'i-fe:edit' }),
          },
        ),

        h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left: 12px;',
            onClick: () => handleDelete(row),
          },
          {
            default: () => '删除',
            icon: () => h('i', { class: 'i-material-symbols:delete-outline text-14' }),
          },
        ),
      ]
    },
  },

]

 
function setStatus(item){
    // console.log(item)
    if(item.status)
        return h('span', { style: { color: 'green' } },'启用')
    else
        return h('span', { style: { color: 'red' } },'禁用')
}

const data: any = ref([])
const rechargeList: any = ref([])
const rechargeShow = ref(false)
 

async function rechargeAdd(){
 
  const res: any = await api.rechargeApi({
    ...rechargeDataItem.value,
    openid:openid.value,
    phone:'',
    merchant_number:"",
    payment_number:"",
    paymentStatus:'1'
  })
  if(res.code == 200){
    $message.success('充值成功!')
    rechargeShow.value = false
  }else{
    
  }

}
 
async function handleDelete(item){
 
  const res: any = await api.DeleteApi({
    id:item.id,
    user_id:route.query.user_id
  })
  if(res.code == 200){
    List();
    $message.success('删除成功!')
  }else{
    
  }

}
const messageParams: any = ref({
  show: false,
  status: '403',
  loading: true,
})

const handleOpenRolesSet =(item) =>{
    formValue.value = item;
    formValue.value.sort = String(formValue.value.sort) 
    formValue.value.currency_balance = String(formValue.value.currency_balance) 
    formValue.value.give_cash = String(formValue.value.give_cash) 
    formValue.value.payment_cash = String(formValue.value.payment_cash) 
        
    popTitle.value = '编辑';
    showModal.value = true;
} 

async function List() {
  try {
    messageParams.value.loading = true
    const res: any = await api.ListApi(params.value)
    if (res.code == 200) {
      messageParams.value.loading = false
      pagination.value.total = res.data.total
      data.value = res.data.list
       
    }
    else {
      messageParams.value.show = false
      messageParams.value.status = '500'
    }
  }
  catch (error) {
    console.error(error)
  }
}
function onClickAdd(){
  popTitle.value = '添加充值'
  showModal.value = true
  formValue.value = {
    currency_balance:"",
    payment_cash:"",
    give_cash:"",
    recharge_type:null,
    JSONData:"",
    channel:null,
    status:true,
    sort:"",
  }
}
async function submitCallback() {
    messageParams.value.loading = true
    formRef.value?.validate((errors) => {
        if (!errors) {
        formValue.value.user_id = route.query.user_id
        formValue.value.plugin_id = route.query.plugin_id
        if(popTitle.value == '添加充值')
            AddFun();
        else
            EditFun();
        }
        else {
        showModal.value = true
        return 
    
        }
    })
}

async function AddFun(){
    
    const newData =  formValue.value
    newData.otherConfigJson = JSON.stringify(formValue.value.otherConfigJson)
    const res: any = await api.AddApi(newData)
    if(res.code == 200){
        List();
        $message.success('添加成功!')
    }else{
        $message.error(res.message)
    }
}

async function EditFun(){
  const res: any = await api.EditApi(formValue.value)
  if(res.code == 200){
    List();
    $message.success('编辑成功!')
  }else{
    $message.error(res.message)
  }
}

function pageNext(page){
  params.value.pageNum = page
  List();
}
function sizeNext(size){
    params.value.pageNum = 1
    params.value.pageSize = size
    List();
}


function cancelCallback() {
  List();
  showModal.value = false
}

function goTo(path){
    router.push(path)
}

function toStore(item){
    router.push({
      path:'/plugin/goodsPlugin/index',
      query:{
        user_id:route.query.user_id,
        store_id:item.businessId,
      }
    })
    // router.push('/plugin/goodsPlugin/index')
}
</script>

<style scoped>
 .box {
    height: 75vh;
    overflow-y: auto;
}
.table-box{
  padding: 20px;
}
.box-modal{
  width: 410px;
  /* height: 550px; */
  
  overflow-y: auto;
}
.pagination{
  display: flex;
  justify-content: right;
  /* height: 60px; */
  gap: 10px;
  align-items: center;
  position: relative;
  top: 20px;
}
.header{
  display: flex;gap: 10px;
}
.Message{
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 200px;
}
.imageUpload{
  width:100px;
  height:100px;
  border:1px solid #eee;
  display: flex;
  justify-content: center;
  border-radius: 6px;
  align-items: center;
}
.imageUpload:hover{
  border:1px solid rgb(49, 108, 114);
}
.rechargeBox{
  display: grid;
  grid-template-columns: repeat(4, 1fr);   
  grid-auto-rows: 80px;   
  gap: 20px;
}
.rechargeItem{
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  width:180px;
  height:80px;
}
.box-recharge{
  height: 450px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
</style>
